package com.atguigu.chapter06;

import com.atguigu.Bean.UserBehavior;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;
import org.junit.Test;

import java.util.HashMap;
import java.util.HashSet;

/**
 * @ClassName: Flink01_Web_PV
 * @Description:
 * @Author: kele
 * @Date: 2021/4/6 18:31
 *
 * project1：
 *   统计用户
 *
 *   数据来源：UserBehavior.csv
 *
 *   1、读取数据
 *   2、将数据封装为UserBehavior类型
 *      过滤出pv的数据，
 *      返回<"uv",id>  //用来保障数据进入同一个通道
 *   3、去重，统计结果
 *
 *
 **/
public class Flink01_Web_UV {

    @Test
    public void Method1() {

        Configuration conf = new Configuration();
        conf.setInteger("rest.port",20000);

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(2);

        DataStreamSource<String> ds = env.readTextFile("in/UserBehavior.csv");

        ds.flatMap(new FlatMapFunction<String, Tuple2<String,Long>>() {
            @Override
            public void flatMap(String value, Collector<Tuple2<String, Long>> out) throws Exception {

                String[] info = value.split(",");

                UserBehavior userBehavior = new UserBehavior(Long.valueOf(info[0]),
                        Long.valueOf(info[1]),
                        Integer.valueOf(info[2]),
                        info[3],
                        Long.valueOf(info[4])
                );

                if("pv".equals(userBehavior.getBehavior())){
                    out.collect(Tuple2.of("uv",userBehavior.getUserId()));
                }
            }
        })
                .keyBy(d->d.f0)
                .process(new KeyedProcessFunction<String, Tuple2<String, Long>, Long>() {

                    HashSet<Long> set = new HashSet<>();
                    @Override
                    public void processElement(Tuple2<String, Long> value,
                                               Context ctx,
                                               Collector<Long> out) throws Exception {

                        if (set.add(value.f1)) {
                            out.collect((long)set.size());
                        }

                    }
                }).print();




        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }





}
